#include "rfidthread.h"
#include "mainWidget.h"
#include "UtilityClass.h"
#include <QString>
#include <QDebug>
//#pragma comment(lib, "GReader")

int ant = 0;
QString epc;
QString curtime;
QString lasttime;

void __stdcall TagEpcLog(char* readerName, LogBaseEpcInfo msg)
{
    ant = msg.AntId;
    epc = QString("EPCXY001001") + QString::fromUtf8(reinterpret_cast<const char*>(msg.Epc)).right(4);
    curtime = getCurrentTime();
    qDebug()<<curtime<<":"<<epc;
}

void __stdcall TagEpcOver(char* readerName, LogBaseEpcOver msg)
{
    qDebug()<<"EPC log error";
}


RFIDThread::RFIDThread(QObject *parent) : QThread(parent)
{
    gclient = OpenRS232("COM1:115200", 5);
    if (gclient == NULL)
    {
        qDebug()<<"Failed to open RS232 connection.";
        throw std::runtime_error("Failed to open RS232 connection.");
    }
    //Debug log
    gclient->isPrint = TRUE;
    RegCallBack(gclient, ETagEpcLog, (void*)TagEpcLog);
    RegCallBack(gclient, ETagEpcOver, (void*)TagEpcOver);

    memset(&stopMsg, 0, sizeof(stopMsg));
    SendSynMsg(gclient, EMESS_BaseStop, &stopMsg);
}

RFIDThread::~RFIDThread()
{
    qDebug()<<"TCP Disconnected! \n";
    Close(gclient);
}

void RFIDThread::stop()
{
    memset(&stopMsg, 0, sizeof(stopMsg));
    SendSynMsg(gclient, EMESS_BaseStop, &stopMsg);
    isrunning = false;
    ant = 0;
}
QVector<AntennaNo> ANT_Vec = {AntennaNo_1, AntennaNo_2, AntennaNo_3, AntennaNo_4,
                              AntennaNo_5, AntennaNo_6, AntennaNo_7, AntennaNo_8};
void RFIDThread::run()
{
    isrunning = true;
    while (isrunning) {
        for(int i = 0; i < 8; i++) {
            memset(&stopMsg, 0, sizeof(stopMsg));
            SendSynMsg(gclient, EMESS_BaseStop, &stopMsg);
            MsgBaseInventoryEpc msg;
            memset(&msg, 0, sizeof(msg));
            msg.AntennaEnable = ANT_Vec.at(i);
            msg.InventoryMode = 1;
            SendSynMsg(gclient, EMESS_BaseInventoryEpc, &msg);
            if(isrunning && ant != 0 && curtime != lasttime) {
                emit curNum(ant, curtime, epc);
                lasttime = curtime;
            }
            if(!isrunning) {
                memset(&stopMsg, 0, sizeof(stopMsg));
                SendSynMsg(gclient, EMESS_BaseStop, &stopMsg);
                return;
            }
        }
    }
}
